package com.wyw.quartz.learning.service.impl;

import com.wyw.quartz.learning.common.job.DynamicJob;
import com.wyw.quartz.learning.entity.JobEntity;
import com.wyw.quartz.learning.repository.JobEntityRepository;
import com.wyw.quartz.learning.service.DynamicJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Title
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * @Date 2024/3/29 17:55
 * Update History:
 * Author        Time            Content
 */
@Service
public class DynamicJobServiceImpl implements DynamicJobService {
    @Autowired
    private JobEntityRepository repository;

    @Override
    public JobEntity getJobEntityById(Long id) {
        return repository.getById(id);
    }

    @Override
    public List<JobEntity> loadJobs() {
        return repository.findAll();
    }

    @Override
    public JobDataMap getJobDataMap(JobEntity job) {
        JobDataMap map = new JobDataMap();
        map.put("name", job.getName());
        map.put("jobGroup", job.getJobGroup());
        map.put("cronExpression", job.getCron());
        map.put("parameter", job.getParameter());
        map.put("jobDescription", job.getDescription());
        map.put("orderStatus", job.getOrderStatus());
        map.put("url", job.getUrl());
        map.put("status", job.getStatus());
        return map;
    }

    @Override
    public JobDetail getJobDetail(JobKey jobKey, String description, JobDataMap map) {
        return JobBuilder.newJob(DynamicJob.class)
                .withIdentity(jobKey)
                .withDescription(description)
                .setJobData(map)
                .storeDurably()
                .build();
    }

    @Override
    public Trigger getTrigger(JobEntity job) {
        return TriggerBuilder.newTrigger()
                .withIdentity(job.getName(), job.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                .build();
    }

    @Override
    public JobKey getJobKey(JobEntity job) {
        return JobKey.jobKey(job.getName(), job.getJobGroup());
    }
}
